package com.zzyl.nursing.service.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.aliyun.iot20180120.Client;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusRequest;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusResponse;
import com.aliyun.iot20180120.models.QueryDevicePropertyStatusResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.TimeUtil;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.config.properties.AliIoTConfigProperties;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.AddFamilyMemberRequest;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.mapper.ElderMapper;
import com.zzyl.nursing.mapper.FamilyMemberElderMapper;
import com.zzyl.nursing.service.WechatService;
import com.zzyl.nursing.vo.ElderInfoVO;
import com.zzyl.nursing.vo.LoginVo;
import com.zzyl.nursing.vo.QueryDeviceDataListByDayVo;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.stream.Collectors;

/**
 * 老人家属Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-19
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper,FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private Client client;

    @Autowired
    private WechatService wechatService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private FamilyMemberElderMapper familyMemberElderMapper;

    @Autowired
    private AliIoTConfigProperties aliIoTConfigProperties;

    static List<String> DEFAULT_NICK_NAME = ListUtil.of(
            "生活更美好",
            "大桔大利",
            "日富一日",
            "好柿开花",
            "柿柿如意",
            "一椰暴富",
            "大柚所为",
            "杨梅吐气",
            "天生荔枝");

    /**
     * 小程序登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {

        //1.获取openid(调用微信的接口获取) ***
        String openid = wechatService.getOpenid(dto.getCode());

        //2.根据openid查询用户
        LambdaQueryWrapper<FamilyMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(FamilyMember::getOpenId, openid);
        FamilyMember familyMember = getOne(queryWrapper);

        //3.判断用户是否存在，用户不存在，就构建用户
        if (ObjectUtil.isEmpty(familyMember)) {
            /*familyMember = new FamilyMember();
            familyMember.setOpenId(openid);*/
            familyMember = FamilyMember.builder()
                    .openId(openid)
                    .build();
        }

        //4.获取用户的手机号（调用微信的接口获取）***
        String phone = wechatService.getPhone(dto.getPhoneCode());

        //5. 新增或修改用户
        inserOrUpdateFamilyMember(familyMember, phone);

        //6. 把用户的信息封装到token,返回
        Map<String, Object> claims = new HashMap<>();
        claims.put("username", familyMember.getName());
        claims.put("userId", familyMember.getId());
        String token = tokenService.createToken(claims);

        LoginVo loginVo = new LoginVo();
        loginVo.setToken(token);
        loginVo.setNickName(familyMember.getName());

        return loginVo;
    }

    /**
     * 新增或修改用户
     *
     * @param familyMember
     * @param phone
     */
    private void inserOrUpdateFamilyMember(FamilyMember familyMember, String phone) {

        //1. 判断新的手机跟数据库中保存的手机号是否一致
        if (ObjectUtil.notEqual(familyMember.getPhone(), phone)) {
            familyMember.setPhone(phone);
        }

        //2. id是否存在，如存在，就修改
        if (ObjectUtil.isNotEmpty(familyMember.getId())) {
            updateById(familyMember);
            return;
        }

        //3. 不存在，就新增 (拼装用户的昵称：随机字符串+手机号后4位)
        int index = (int) (Math.random() * DEFAULT_NICK_NAME.size());
        String nickName = DEFAULT_NICK_NAME.get(index) + phone.substring(phone.length() - 4);
        familyMember.setName(nickName);
        save(familyMember);

    }

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }


    /**
     * 绑定家人
     *
     * @param elder
     * @return
     */
    @Override
    public void addFamilyMember(AddFamilyMemberRequest elder) {
        //根据前端输入的老人身份证号获取老人ID，根据elder.getIdCard()查询elderMapper中id
        Elder elder1 = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, elder.getIdCard()));
        //判断老人ID是否为空，如果为空抛出异常为老人未注册
        if (ObjectUtil.isEmpty(elder1)) {
            throw new RuntimeException("老人未注册");
        }
        //判断前端输入的老人姓名是否与老人ID是否一致，如果不一致抛出异常为信息不匹配
        if (!elder.getName().equals(elder1.getName())) {
            throw new RuntimeException("信息错误，请认真核对");
        }
        //获取当前用户ID
        Long userId = UserThreadLocal.getUserId();
        //判断老人ID是否已绑定，如果已绑定抛出异常为老人已绑定
        FamilyMemberElder familyMemberElder = familyMemberElderMapper.selectOne(Wrappers.<FamilyMemberElder>lambdaQuery().eq(FamilyMemberElder::getElderId, elder1.getId()));
        if (ObjectUtil.isNotEmpty(familyMemberElder)) {
            throw new RuntimeException("老人已绑定");
        }

        //封装信息到FamilyMemberElder表中
        FamilyMemberElder familyMemberElder1 = new FamilyMemberElder().builder()
                .createBy(userId)
                .createTime(LocalDateTime.now())
                .elderId(elder1.getId())
                .familyMemberId(userId)
                .remark(elder.getRemark())
                .updateBy(userId)
                .updateTime(LocalDateTime.now())
                .build();
        familyMemberElderMapper.insert(familyMemberElder1);
    }

    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public List<ElderInfoVO> selectPage(int pageNum, int pageSize) {
        Long userId = UserThreadLocal.getUserId();
        List<ElderInfoVO> elderInfoVOS = familyMemberMapper.selectPageAll(pageNum, pageSize, userId);
        return elderInfoVOS;
    }

    @Override
    public QueryDevicePropertyStatusResponseBody.QueryDevicePropertyStatusResponseBodyData QueryDevicePropertyStatus(Device device) {
        System.out.println(device.getProductKey());
        System.out.println(device.getDeviceName());
        QueryDevicePropertyStatusRequest request = new QueryDevicePropertyStatusRequest();
        request.setProductKey(device.getProductKey());
        request.setDeviceName(device.getDeviceName());
        request.setIotInstanceId(aliIoTConfigProperties.getIotInstanceId());
        QueryDevicePropertyStatusResponse response;
        try {
            response = client.queryDevicePropertyStatus(request);
            if (response.getBody().success) {
                System.out.println(JSON.toJSONString(response.getBody().data));
                QueryDevicePropertyStatusResponseBody.QueryDevicePropertyStatusResponseBodyData data = response.getBody().data;
                return data;
            } else {
                System.out.println(response.getBody().errorMessage);
                throw new BaseException(response.getBody().getErrorMessage());
            }
        } catch (Exception e) {
            throw new BaseException("网络波动，请联系管理员");
        }
    }

    @Override
    public List<QueryDeviceDataListByDayVo> queryDeviceDataListByDay(DeviceDataRequest request) {
//        // 查询数据库获取原始数据点
//        List<QueryDeviceDataListByDayVo> rawDataPoints = familyMemberMapper.queryDeviceDataListByDay(
//                request.getIotId(),
//                request.getFunctionId(),
//                request.getStartTime(),
//                request.getEndTime()
//        );
//
//// 构造响应对象
//        DeviceDataResponse response = new DeviceDataResponse();
//        response.setCode(200);
//        response.setMsg("操作成功");
//
//// 格式化时间戳为HH:mm格式
//        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
//
//// 如果 SQL 查询返回的是完整的日期时间字符串（例如 'YYYY-MM-DD HH:00'），则可以这样处理：
//        DateTimeFormatter sqlFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
//
//        response.setData(rawDataPoints.stream()
//                .filter(dp -> dp.getDateTime() != null && dp.getDataValue() != null) // 确保 dateTime 和 dataValue 都不为空
//                .map(dp -> {
//                    QueryDeviceDataListByDayVo dataPoint = new QueryDeviceDataListByDayVo();
//
//                    // 解析并格式化 dateTime 字符串
//                    LocalDateTime dateTime = LocalDateTime.parse(dp.getDateTime(), sqlFormatter);
//                    dataPoint.setDateTime(dateTime.format(formatter));
//
//                    // 设置 dataValue
//                    dataPoint.setDataValue(dp.getDataValue());
//
//                    System.out.println(dataPoint + "=========================================================================================================================");
//                    return dataPoint;
//                })
//                .collect(Collectors.toList()));

//        return response;

        Long endTime = request.getEndTime();
        System.out.println(endTime+"=====================endTime==============================");

        // 将时间戳转换为 Instant
        Instant instant = Instant.ofEpochMilli(endTime);
        // 将 Instant 转换为 LocalDateTime，指定时区为中国标准时间 (CST)
        LocalDateTime endLocalDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        Long startTime = request.getStartTime();
        // 将时间戳转换为 Instant
        Instant instant1 = Instant.ofEpochMilli(startTime);
        // 将 Instant 转换为 LocalDateTime，指定时区为中国标准时间 (CST)
        LocalDateTime startLocalDateTime = instant1.atZone(ZoneId.systemDefault()).toLocalDateTime();
        System.out.println(startLocalDateTime+"=====================startLocalDateTime==============================");
        System.out.println(endLocalDateTime+"=====================endLocalDateTime==============================");

        List<QueryDeviceDataListByDayVo> queryDeviceDataListByDayVos = familyMemberMapper.queryDeviceDataListByDayxixi(request.getIotId(), request.getFunctionId(), startLocalDateTime, endLocalDateTime);
        System.out.println(queryDeviceDataListByDayVos+"==================-===============----------------------------");


        return queryDeviceDataListByDayVos;
    }


    @Override
    public List<QueryDeviceDataListByDayVo> queryDeviceDataListByDayXiXi(DeviceDataRequest request) {

        Long endTime = request.getEndTime();
        System.out.println(endTime+"=====================endTime==============================");

        // 将时间戳转换为 Instant
        Instant instant = Instant.ofEpochMilli(endTime);
        // 将 Instant 转换为 LocalDateTime，指定时区为中国标准时间 (CST)
        LocalDateTime endLocalDateTime = instant.atZone(ZoneId.systemDefault()).toLocalDateTime();
        Long startTime = request.getStartTime();
        // 将时间戳转换为 Instant
        Instant instant1 = Instant.ofEpochMilli(startTime);
        // 将 Instant 转换为 LocalDateTime，指定时区为中国标准时间 (CST)
        LocalDateTime startLocalDateTime = instant1.atZone(ZoneId.systemDefault()).toLocalDateTime();

        List<QueryDeviceDataListByDayVo> queryDeviceDataListByDayVos = familyMemberMapper.queryDeviceDataListByDayGaga(request.getIotId(), request.getFunctionId(), startLocalDateTime, endLocalDateTime);
        System.out.println(queryDeviceDataListByDayVos+"==================-===============----------------------------");



//        return queryDeviceDataListByDayVos;
        return queryDeviceDataListByDayVos;
    }

    @Override
    public void deleteByIdelder(Long id) {
        familyMemberMapper.deleteByIdelder(id);
    }
}
